using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
//using Helpers;

namespace TextOverlay
{
    /// <summary>
    /// Use this to broadcast sync messages system-wide
    /// </summary>
    class UDPBroadcast
    {
        //private static IPAddress GroupAddress = IPAddress.Parse("224.168.100.2");
        private IPAddress GroupAddress = IPAddress.Parse("255.255.255.255");
        private int GroupPort = 5555;
        private UdpClient TheClient;
        private IPEndPoint groupEP;

        public UDPBroadcast(string IP)
        {
            if (IP.Length == 0)
                Track.LogInfo("Error: No Control IP in MagnoliaSCS.ini!");
            IPEndPoint LocalEP = new IPEndPoint(IPAddress.Parse(IP /*"127.0.01"*/), 0);
            TheClient = new UdpClient(LocalEP);
            groupEP = new IPEndPoint(GroupAddress, GroupPort);
        }

        private void Destroy()
        {
            TheClient.Close();
        }

        /// <summary>
        /// send the last string set with SetBytes(message)
        /// 
        /// </summary>
        public void Send(String str)
        {
            byte[] BroadcastMessage = Encoding.ASCII.GetBytes(str);

            if (BroadcastMessage != null && TheClient != null)
            {
                try
                {
                    TheClient.Send(BroadcastMessage, BroadcastMessage.Length, groupEP);
                }
                catch 
                {
                    //Global.TRACE(e.ToString());
                }
            }
        }
    }
}
